package com.example.web.controller;

import com.example.api.vo.UserApiVO;
import com.example.common.util.RequestContext;
import com.example.common.vo.ApiResponse;
import com.example.common.vo.PageResponse;
import com.example.query.UserQuery;
import com.example.service.UserService;
import com.example.web.vo.UserQueryVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户控制器
 * 主要职责：请求转发、基础参数校验，仅处理简单且无需复用的业务逻辑
 * 遵循API规范：必须包含requestId和version字段，使用统一响应格式
 * 
 * @author AI Assistant
 * @since 1.0.0
 */
@Api(tags = "用户管理API")
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 分页查询用户列表
     * 
     * @param query 查询条件
     * @param requestId 请求ID
     * @param version 版本号
     * @return 用户分页数据
     */
    @ApiOperation(value = "分页查询用户列表", notes = "支持多条件模糊查询，分页返回用户列表")
    @GetMapping("/list")
    public ApiResponse<PageResponse<UserApiVO>> queryUserPage(
            UserQuery query,
            @ApiParam(value = "请求ID", example = "req-20240520-8f7d9a0b") @RequestParam(required = false) String requestId,
            @ApiParam(value = "版本号", example = "1.0.0") @RequestParam(defaultValue = "1.0.0") String version) {
        
        // 初始化请求上下文
        if (requestId == null || requestId.isEmpty()) {
            requestId = RequestContext.generateRequestId();
        } else {
            RequestContext.setRequestId(requestId);
        }
        RequestContext.setVersion(version);
        
        log.info("接收到用户列表查询请求，requestId={}, version={}, 查询条件：{}", requestId, version, query);
        
        try {
            // 基础参数校验
            if (query.getPageNum() == null || query.getPageNum() < 1) {
                query.setPageNum(1);
            }
            if (query.getPageSize() == null || query.getPageSize() < 1) {
                query.setPageSize(10);
            }
            if (query.getPageSize() > 100) {
                query.setPageSize(100);
            }
            
            // 调用服务层
            com.baomidou.mybatisplus.core.metadata.IPage<UserQueryVO> userPage = userService.queryUserPage(query);
            
            // 转换为API响应对象
            List<UserApiVO> apiVOList = userPage.getRecords().stream()
                    .map(this::convertToApiVO)
                    .collect(Collectors.toList());
            
            PageResponse<UserApiVO> pageResponse = new PageResponse<>(
                    apiVOList,
                    userPage.getTotal(),
                    userPage.getSize(),
                    userPage.getCurrent(),
                    userPage.getPages()
            );
            
            log.info("用户列表查询成功，requestId={}, 返回{}条记录", requestId, userPage.getTotal());
            return ApiResponse.success(pageResponse, requestId, version);
            
        } catch (Exception e) {
            log.error("用户列表查询异常，requestId={}", requestId, e);
            return ApiResponse.systemError("查询用户列表失败", requestId, version);
        } finally {
            RequestContext.clear();
        }
    }
    
    /**
     * 根据ID查询用户详情
     * 
     * @param id 用户ID
     * @param requestId 请求ID
     * @param version 版本号
     * @return 用户详情
     */
    @ApiOperation(value = "根据ID查询用户详情", notes = "根据用户ID查询用户详细信息")
    @GetMapping("/{id}")
    public ApiResponse<UserApiVO> getUserById(
            @PathVariable Long id,
            @ApiParam(value = "请求ID", example = "req-20240520-8f7d9a0b") @RequestParam(required = false) String requestId,
            @ApiParam(value = "版本号", example = "1.0.0") @RequestParam(defaultValue = "1.0.0") String version) {
        
        // 初始化请求上下文
        if (requestId == null || requestId.isEmpty()) {
            requestId = RequestContext.generateRequestId();
        } else {
            RequestContext.setRequestId(requestId);
        }
        RequestContext.setVersion(version);
        
        log.info("接收到用户详情查询请求，requestId={}, version={}, 用户ID：{}", requestId, version, id);
        
        try {
            // 基础参数校验
            if (id == null || id <= 0) {
                return ApiResponse.badRequest("用户ID不能为空且必须大于0", requestId, version);
            }
            
            // 调用服务层
            UserQueryVO userVO = userService.getUserById(id);
            if (userVO == null) {
                return ApiResponse.error(404, "用户不存在", requestId, version);
            }
            
            // 转换为API响应对象
            UserApiVO apiVO = convertToApiVO(userVO);
            
            log.info("用户详情查询成功，requestId={}, 用户ID：{}", requestId, id);
            return ApiResponse.success(apiVO, requestId, version);
            
        } catch (Exception e) {
            log.error("用户详情查询异常，requestId={}, 用户ID：{}", requestId, id, e);
            return ApiResponse.systemError("查询用户详情失败", requestId, version);
        } finally {
            RequestContext.clear();
        }
    }
    
    /**
     * 将UserQueryVO转换为UserApiVO
     * 
     * @param userVO 用户查询VO
     * @return 用户API VO
     */
    private UserApiVO convertToApiVO(UserQueryVO userVO) {
        UserApiVO apiVO = new UserApiVO();
        BeanUtils.copyProperties(userVO, apiVO);
        return apiVO;
    }
}

